<?php
/**********************************************************************************
WIKINDX: Bibliographic Management system.
Copyright (C)

This program is free software; you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program;
if not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

The WIKINDX Team 2006
sirfragalot@users.sourceforge.net
**********************************************************************************/
/*****
* FILE class
*
*****/
class FILE
{
// Constructor
	function FILE($db)
	{
		$this->db = $db;
		include_once("core/messages/MESSAGES.php");
		$this->messages = new MESSAGES();
		include_once("core/template/TEMPLATE.php");
		$this->template = new TEMPLATE('content');
		include_once("core/session/SESSION.php");
		$this->session = new SESSION();
		$this->pString = '';
		include("config.php");
		if(!isset($WIKINDX_PAPERS_DIR))
			$this->dirPapersName = "papers";
		else
			$this->dirPapersName = $WIKINDX_PAPERS_DIR;
		if(!isset($WIKINDX_FILES_DIR))
			$this->dirName = "files";
		else
			$this->dirName = $WIKINDX_FILES_DIR;
	}
// For file exports saved outside web server directory (i.e. not in wikindx3/files/) as set in config.php
	function exportDownload($vars)
	{
		$this->vars = $vars;
		if(!array_key_exists('hash', $this->vars))
			$this->badInput($this->errors->text("inputError", "missing"));
		$extension = $this->vars['extension'];
		$fileName = $this->vars['filename'];
		if($this->vars['extension'] == 'rtf')
			$type = 'text/rtf';
		else
			$type = 'text/text';
		ob_start();
		header("Content-type: $type");
		header( "Content-Disposition: inline; filename=\"$fileName\";" );
		header("Expires:  0");
		header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
		header("Pragma: public");
		readfile($this->dirName . "/" . $this->vars['hash'] . "." . $extension);
		ob_end_flush();
		die;
	}
// If $noMenu, display Resources submenu links
	function display($noMenu = FALSE)
	{
		include_once("core/html/MISC.php");
		$this->template->setVar('heading', $this->messages->text("heading", "files"));
		if($noMenu)
		{
			include_once("core/html/MENU.php");
			$menu = new MENU();
			$pString = $menu->noMenu('file');
			$this->template->setVar('noMenu', $pString);
			return $this->template->process();
		}
		$this->template->setVar('body', $pString);
		return $this->template->process();
	}
// tidy up the files directory by removing all files and folders older than 'setup_fileDeleteSeconds'
	function tidyFiles()
	{
// failure is an option;
		if(!$dh = @opendir($this->dirName))
			return;
		$now = time();
		$maxTime = $this->session->getVar('setup_fileDeleteSeconds');
		$fileArray = array();
		while(false !== ($f = readdir($dh)))
		{
			if(($f == ".") || ($f == "..") || ($f == 'CVS') || ($f == 'FILES'))
				continue;
			$file = $this->dirName . '/' . $f;
			if(($now - filemtime($file)) >= $maxTime)
			{
				@unlink($file);
				$fileArray[] = $f;
			}
		}
// Remove reference to these files in session
		if(!empty($fileArray))
		{
			if($sessVar = $this->session->getVar('fileExports'))
			{
				$sessArray = unserialize($sessVar);
				foreach($fileArray as $f)
					unset($sessArray[array_search($f, $sessArray)]);
				if(!empty($sessArray))
					$this->session->setVar('fileExports', serialize($sessArray));
				else
					$this->session->delVar('fileExports');
			}
			if($sessVar = $this->session->getVar('paperExports'))
			{
				$sessArray = unserialize($sessVar);
				foreach($fileArray as $f)
					unset($sessArray[$f]);
				if(!empty($sessArray))
					$this->session->setVar('paperExports', serialize($sessArray));
				else
					$this->session->delVar('paperExports');
			}
		}
// Specific to the demo version at www.sirfragalot.com/wikindx3/
// Remove papers belonging to the guest user.
		global $WIKINDX_RESTRICT_USER;
		include_once("core/html/HTML.php");
		$html = new HTML();
		$papers = array();
		$recordSet = $this->db->select(array("WKX_papers"), array("id", "hashFilename"), 
			" WHERE " . $this->db->formatField("userId") . "=" . $this->db->tidyInput($WIKINDX_RESTRICT_USER));
		while($row = $this->db->loopRecordSet($recordSet))
			$papers[$row['id']] = $html->dbToFormTidy($row['hashFilename']);
		foreach($papers as $id => $hashfilename)
		{
			$file = $this->dirPapersName . '/' . $hashfilename;
			if(($now - filemtime($file)) >= $maxTime)
			{
				@unlink($file);
				$this->db->delete("WKX_papers", 
				" WHERE " . $this->db->formatField('id') . '=' . $this->db->tidyInput($id));
			}
		}	
		$this->db->optimize("WKX_papers");
	}
// list and HTML format all files for sessionID
	function listFiles()
	{
		$fileExports = $this->session->getVar('fileExports');
		$paperExports = $this->session->getVar('paperExports');
		if((!$dh = @opendir($this->dirName)) || (!$fileExports && !$paperExports))
			return array(FALSE, FALSE, FALSE, FALSE, FALSE);
		$fileArray = $paperArray = $paperTemp = $extensions = array();
		if($fileExports)
		{
			$sessArray = unserialize($fileExports);
			while(FALSE !== ($file = readdir($dh)))
			{
				if($file == "." || $file == "..")
					continue;
				if(array_search($file, $sessArray) === FALSE)
					continue;
// list only BibTeX, XML, RIS, TXT (Endnote), HTML, gz and RTF files
				if(!preg_match("/\.bib|\.xml|\.rtf|\.ref|\.txt|\.html|\.gz/", $file))
					continue;
				$fileArray[$file] = filemtime($this->dirName . '/' . $file);
			}
			asort($fileArray, SORT_NUMERIC);
			$fileArray = array_reverse($fileArray);
		}
		if($paperExports)
		{
			$sessArray = unserialize($paperExports);
			foreach($sessArray as $hash => $title)
			{
				$titleParts = explode('.', strrev($title), 2);
				$title = strrev($titleParts[1]);
				$extension = strrev($titleParts[0]);
				$hashPath = $this->dirName . '/' . $hash . ".$extension";
				if(!file_exists($hashPath))
					continue;
				$extensions[] = $extension;
				$paperTemp[$hash] = filemtime($hashPath);
			}
			asort($paperArray, SORT_NUMERIC);
			$paperTemp = array_reverse($paperTemp);
			foreach($paperTemp as $hash => $mTime)
				$paperArray[$hash] = $sessArray[$hash];
		}
		closedir($dh);
		return array($this->dirName, $this->session->getVar('setup_fileDeleteSeconds'), 
			$fileArray, $paperArray, $extensions);
	}
// create a fileName for this file.  If directory based on session ID does not exist, create it.
	function createFileName($string, $extension)
	{
		$fileName = sha1(session_id() . $string) . $extension;
		return array($fileName, $this->dirName . '/' . $fileName);
	}
// delete folder and all files within it
	function deleteAll($type, $id)
	{
		if(!$dh = @opendir($this->dirName))
			return;
		while(false !== ($file = readdir($dh)))
		{
			if ($file != "." && $file != "..")
				unlink($this->dirName . '/' . $file);
		}
		closedir($dh);
	}
// Show all files in temporary directory (called from File menu)
	function show()
	{
		$this->template->setVar('heading', $this->messages->text("heading", "files"));
		list($dirName, $deletePeriod, $fileArray, $paperArray, $extensions) = $this->listFiles();
		if(empty($fileArray) && empty($paperArray))
		{
			include_once("core/messages/ERRORS.php");
			$errors = new ERRORS();
			$this->template->setVar('body', $errors->text("file", "empty"));
			return $this->template->process();
		}
		$pString = MISC::p($this->messages->text("file", "contents"));
		$minutes = $deletePeriod/60;
		if(!empty($fileArray))
		{
			$pString .= $this->messages->text("file", "bibliographies") . MISC::br();
			foreach($fileArray AS $key => $value)
			{
				if($dirName == 'files')
					$pString .= MISC::a("link", $key, $dirName . '/' . $key, "_blank") . MISC::br();
				else // using FILES directory in config.php so possibly outside of web server htdocs/
				{
					$split = explode(".", $key);
					$title = $split[0];
					$extension = $split[1];
					$pString .= MISC::a("link", $key, "index.php?action=exportDownload" . 
						htmlentities("&hash=$title&filename=$key&extension=$extension"), "_new") . MISC::br();
				}
			}
//				$pString .= MISC::a("link", $key, $dirName . '/' . $key, "_blank") . MISC::br();
			if(!empty($paperArray))
				$pString .= MISC::hr();
		}
		if(!empty($paperArray))
		{
			$pString .= $this->messages->text("file", "papers") . MISC::br();
			foreach($paperArray AS $fileName => $title)
			{
				$extension = array_shift($extensions);
				$titleUrl = rawurlencode($title);
				$pString .= MISC::a("link", $title, "index.php?action=wpExportDownload" . 
					htmlentities("&hash=$fileName&filename=$titleUrl&extension=$extension"), "_new") . 
					MISC::br();
			}
		}
		$pString .= MISC::hr();
		$pString .= MISC::p($this->messages->text("file", "warning", " $minutes "));
		$this->template->setVar('body', $pString);
		return $this->template->process();
	}
}
?>
